'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 官阶俸禄
 * @author sundbcn@gmail.com (sun debing)
 */

var async = require('async');
var Code = require('../../../../consts/code');
var moduleType = require('../../../../consts/moduleType');
var operationType = require('../../../../consts/operationType');
var battleConf = require('../../../../config/battleConf');
var roleService = require('../../../../services/roleService');
var PlayerManager = require('../../../../libs/playerManager');
var rewardService = require('../../../../services/rewardService.js');

module.exports = function (msg, session, next) {
    var role_id = session.uid;

    var player_manager = new PlayerManager(role_id);
    var reward_list = [];
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['role', 'bag', 'build', 'soldier', 'battle', 'task', 'achieve', 'daily_task', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var role_model = player_manager.role;
                var battle_model = player_manager.battle;

                // 判断是否可以领取俸禄
                if (!battle_model.isCanRecieve()) {
                    return next(null, {
                        code: Code.BATTLE_SALARY_HAVE_RECEIVE
                    });
                }

                // 添加俸禄
                reward_list = battleConf.getSalaryRewardConf(role_model.getJob(), battle_model.getNoble());
                if (!reward_list) {
                    return next(null, {
                        code: Code.COPY_REWARD_ERROR
                    });
                }
                rewardService.addRewardListToRole(player_manager, reward_list, moduleType.MDL_PVP, operationType.OPR_PVP_RECEIVE_SALARY);

                // 设置领取时间
                battle_model.resetReceiveSalaryTime();
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    reward_list: reward_list
                }
            });
        }
    );
};
